from flask import Blueprint, request, jsonify  # 导入Blueprint
import pymysql
from dbutils.pooled_db import PooledDB
from datetime import datetime
import sys
import requests
from mysql_utils import get_video_id_by_url, query_video_sources, query_videos_list, is_new_user, insert_openid_by_raceNumber_personId, get_effects_name_by_body_effects_id_and_bg_effects_id

AppID = 'wx001b6f4e30d935d0'
AppSecret = '21e486562dfc30374d85b0995345d716'

# 创建登录相关蓝图
login_bp = Blueprint('login', __name__)
# 用户登录接口
@login_bp.route('/login', methods=['POST'])
def silent_login():
    # 1. 获取小程序传来的code
    code = request.json.get('code')
    if not code:
        return jsonify({'code': 400,
                        'message': '缺少code参数'
                        })

    # 2. 向微信服务器请求openid
    wx_url = f"https://api.weixin.qq.com/sns/jscode2session?appid={AppID}&secret={AppSecret}&js_code={code}&grant_type=authorization_code"
    wx_res = requests.get(wx_url).json()

    # 3. 获取openid和session_key
    openid = wx_res.get('openid')
    session_key = wx_res.get('session_key')
    print(openid,session_key)
    new_user = is_new_user(openid)
    if not openid:
        return jsonify({'code': 401,
                        'message': '获取openid失败'
                        })

    # 4. 这里可以生成自己的登录态token(可选)
    # token = generate_token(openid)
    # 5. 返回必要信息给小程序
    return jsonify({
        'code': 0,
        'openid': openid,
        'session_key': session_key,
        'is_new_user':new_user  #返回值为true 前端显示弹窗  返回值为false 前端不显示弹窗
        # 'token': token
    })

#用户信息校验接口
@login_bp.route("/confirm", methods=["POST"])
def confirm_user():
    openid = request.json.get('openid')
    race_number = request.json.get('race_number')
    name = request.json.get('name')
    nickname = request.json.get('nickname')
    personid = request.json.get('personid')
    phone = request.json.get('phone')
    print(race_number,name,nickname,personid,phone,openid)

    #插入openid根据race_number和personid
    original_video_url = insert_openid_by_raceNumber_personId(openid,race_number,personid)

    return jsonify({
        'code':0,
        'message':'success',
        'data':{
            'video_url':original_video_url
        }
    })

#用户视频列表查询接口
@login_bp.route("/video/list", methods=["GET"])
def get_video_list():
    openid = request.args.get('openid')
    print(openid)
    video_list = query_videos_list(openid)
    result = []
    for video in video_list:
        create_time = video['create_time']
        returnCreateTime = create_time.strftime("%Y-%m-%d %H:%M:%S")
        body_effect_name = get_effects_name_by_body_effects_id_and_bg_effects_id(video['body_effects_id'],video['bg_effects_id'])['body_effects_name']
        bg_effect_name = get_effects_name_by_body_effects_id_and_bg_effects_id(video['body_effects_id'], video['bg_effects_id'])['bg_effects_name']
        item = {
            "video_title":video['video_title'],
            "video_url":video['video_url'],
            "body_effect_name":body_effect_name,  #身体特效名字
            "bg_effect_name":bg_effect_name,     #背景特效名字
            "has_effect":video['with_effects'],
            "body_effect_id":video["body_effects_id"],
            "bg_effect_id":video["bg_effects_id"],
            "handle_number":video['handle_number'],
            "handle_status": video['handle_status'],
            "generate_time":returnCreateTime
        }
        result.append(item)
    return jsonify({
        "code": 0,
        "message": "视频查询成功",
        "data": {
            "openid":openid,
            "videoList":result
        }
    })


